import { defineConfig } from "vite";
import type { PluginOption } from 'vite'
import uni from "@dcloudio/vite-plugin-uni";
import { join, resolve } from "path";
import * as fs from 'fs'
const sleep = (value = 30) =>
	new Promise((resolve) => {
		setTimeout(() => {
			resolve(null);
		}, value);
	});
function renameFile() : PluginOption {
	return {
		name: "renameFile",
		enforce: 'post',
		apply: 'build',
		async writeBundle() {
			if (process.env.UNI_SCRIPT === 'wx-platform' || process.env.UNI_SCRIPT === 'private-platform') {
				await sleep(5000)
				let build_dir = join(__dirname, 'dist/build');
				let web_dir = join(build_dir, 'web');
				let web_dir1 = join(build_dir, process.env.UNI_SCRIPT === 'wx-platform' ? '公众号' : '私域');
				
				try {
					fs.rmSync(web_dir1, { recursive: true });
				} catch (error) { }
				fs.renameSync(web_dir, web_dir1)
				console.log(`自定义发行编译成功，路径为：${web_dir1}`)

			}
		},
	};
}



// https://vitejs.dev/config/
export default defineConfig({
	build: {
		sourcemap: false, //源码调试
		target: ["chrome89", "edge89", "firefox89", "safari15"]
	},
	plugins: [uni(), renameFile()],
	resolve: {
		alias: [
			{
				find: "@",
				replacement: resolve(__dirname, "src"),
			},
			{
				find: "/pages",
				replacement: resolve(__dirname, "src/pages"),
			},
			{
				find: "/static",
				replacement: resolve(__dirname, "src/static"),
			},
		],
	},
});
